<template>
  <div class="app-container">

    <u-page title="预约下载">
      <el-form ref="dialogForm" :model="dataForm" class="search-form" :rules="rules">
        <el-form-item label="数据类型" prop="datatype">
          <el-radio-group v-model="dataForm.datatype">
            <el-radio-button label="smg">扫码购数据</el-radio-button>
            <el-radio-button label="kkd">扣款单数据</el-radio-button>
            <el-radio-button label="cashier">收款员报表</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="数据时间" prop="daterange">
          <u-date-time-picker v-model="dataForm.daterange" type="daterange" value-format="yyyy-MM-dd" :picker-options="pickerOptions" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="sub">创建预约</el-button>
        </el-form-item>
      </el-form>
    </u-page>
    <div style="height:15px;"></div>
    <u-page title="历史预约列表">
      <div slot="header">
        <el-button type="primary" icon="el-icon-refresh" @click="hdlList">
          刷新
        </el-button>
      </div>
      <u-table
        :data="list"
        :loading="listLoading"
        :options="listOptions"
        :columns="columns"
        :pagination.sync="listQuery"
        :fetch="hdlList"
        @selection-change="hdlSelectChange"
      >
        <template v-slot:right>
          <el-table-column label="操作" align="center" fixed="right">
            <template slot-scope="{ row }">
              <el-button v-if="row.status === 1" type="text" @click="downloadAttachment(row)">下载</el-button>
              <el-button v-if="row.status === -1" type="text" @click="handleButtonClick(row)">重新生成</el-button>
            </template>
          </el-table-column>
        </template>
      </u-table>
    </u-page>
  </div>
</template>

<script>
export default {
  data() {
    return {
      api: this.$u.api.DataSubscribe,
      dataForm: {
        beginDate: '',
        endDate: '',
        datatype: 'smg',
        daterange: []
      },
      orderShow: false,
      listQuery: {
        page: 1,
        pageSize: 10,
        totalCount: 1,
        datatype: 'smg'
      },
      rules: {
        daterange: [
          { required: true, message: '时间必选', trigger: 'blur' }
        ]
      },
      // 表格
      columns: [
        {
          prop: 'datatype',
          label: '数据类型',
          render: (h, params) => {
            if (params.row.datatype === 'smg') {
              return h('el-tag', { props: { type: 'success' }}, '扫码购')
            } else if (params.row.datatype === 'kkd') {
              return h('el-tag', { props: { type: 'warning' }}, '扣款单')
            } else if (params.row.datatype === 'cashier') {
              return h('el-tag', { props: { type: 'success' }}, '收款员报表')
            } else {
              return ''
            }
          }
        },
        {
          prop: 'dateRange',
          label: '数据时间',
          formatter: (row) => {
            return row.beginDate + ' 至 ' + row.endDate
          }
        },
        {
          prop: 'createdBy',
          label: '预约人'
        },
        {
          prop: 'createdAt',
          label: '预约时间',
          timestamp: true
        },
        {
          prop: 'updatedAt',
          label: '生成时间',
          timestamp: true
        },
        {
          prop: 'status',
          label: '文件状态',
          render: (h, params) => {
            if (params.row.status === 0) {
              return h('el-tag', { props: { type: 'warning' }}, '生成中')
            } else if (params.row.status === 1) {
              return h('el-tag', { props: { type: 'success' }}, '生成成功')
            } else if (params.row.status === -1) {
              return h('el-tag', { props: { type: 'danger' }}, '生成失败')
            } else {
              return h('el-tag', { props: { type: 'info' }}, '已过期')
            }
          }
        }
      ],
      listLoading: false,
      list: [],
      orderList: [],
      listOptions: {
        stripe: true
      },
      pickerOptions: {
        disabledDate(time) {
          // 获取当前时间
          const now = new Date()
          const currentDate = new Date(now.getFullYear(), now.getMonth(), now.getDate())
          // 获取传入时间的年月日
          const targetDate = new Date(time.getFullYear(), time.getMonth(), time.getDate())
          // 比较日期部分是否在当前日期之后
          return targetDate >= currentDate
        }
      }
    }
  },
  created() {
    this.hdlList()
  },
  methods: {
    handleButtonClick(row) {
      this.api.createData(row)
      this.listLoading = true
      setTimeout(() => {
        this.hdlList()
      }, 2000)
    },
    createData(obj) {
      this.api.createData(obj)
    },
    sub() {
      const { daterange } = this.dataForm
      console.log(daterange)
      if (daterange) {
        const startDate = new Date(daterange[0])
        const endDate = new Date(daterange[1])

        const diffInDays = Math.abs((endDate - startDate) / (1000 * 60 * 60 * 24))
        console.log('日期区间', diffInDays)
        if (diffInDays + 1 > 31) {
          this.$message.warning('所选时间范围不能超过31天')
        } else {
          this.dataForm.beginDate = daterange[0]
          this.dataForm.endDate = daterange[1]

          const self = this
          this.$refs['dialogForm'].validate((valid) => {
            if (valid) {
              // 提交创建数据
              self.api.create(self.dataForm).then((res) => {
                // 刷新数据列表
                self.hdlList()
                // 关闭弹窗状态
                self.dialogFormVisible = false
                // 通知信息
                self.$u.msg('创建成功')

                // 生成数据
                setTimeout(() => {
                  self.createData(res.data)
                }, 2000)
              })
            }
          })
        }
      }
    },

    // 下载
    downloadAttachment(row) {
      const root = this.domain + '/attachment/dataFile/subscribe/'
      const a = document.createElement('a')
      a.href = root + row.filename
      a.download = row.filename// 设置下载文件的名称
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
    }
  }
}
</script>

<style scoped>

</style>
